package cn.mumzone.basic.net.http.callback;


import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

import java.io.IOException;

import cn.mumzone.basic.net.response.BaseResponse;
import retrofit2.Response;
import rx.Subscriber;


/**
 * Author Chaney
 * Date   2017/3/7 上午11:25.
 * EMail  qiuzhenhuan.hi@gmail.com
 */
public abstract class CallBack<T> extends Subscriber<Response<BaseResponse<T>>> {

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onCompleted() {
    }

    @Override
    public void onNext(Response<BaseResponse<T>> response) {

        int httpCode = response.code();

        if (response.isSuccessful() || httpCode == 400 || httpCode == 500 || httpCode == 504) {

            BaseResponse<T> data = response.body();
            if (response.isSuccessful()) {
                if (data.getCode() == 200) {
//                    if (data.getData() == null) {
//                        BaseResponse nullResponse = new BaseResponse();
//                        onError(nullResponse);
//                    } else {
                    onSuccess(data.getData());
//                    }
                } else {
                    onError(data);
                }
            } else {
                try {
                    data = JSON.parseObject(response.errorBody().string(), BaseResponse.class);
                } catch (IOException e) {
                    e.printStackTrace();
                    onParseError(e.getMessage());
                }
                onError(data);
            }

        } else {
            onParseError(String.valueOf(httpCode));
        }
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    protected void onParseError(String msg) {
    }

    public abstract void onSuccess(T t);

    public abstract void onError(BaseResponse response);
}
